<?php
    // +----------------------------------------------------------------------
    // | 海豚PHP框架 [ DolphinPHP ]
    // +----------------------------------------------------------------------
    // | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
    // +----------------------------------------------------------------------
    // | 官方网站: http://dolphinphp.com
    // +----------------------------------------------------------------------
    // | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
    // +----------------------------------------------------------------------

    namespace app\member\admin;


    use app\admin\controller\Admin;
    use app\common\builder\ZBuilder;
    use app\base\model\ProductModel;
    use app\common\utils\UtilTree;
    use app\member\model\CheckDataModel;
    use app\member\model\CheckPresentDataModel;
    use app\member\model\MemberInfoModel;
    use app\member\model\MemberModel;
    use app\base\model\WalletProductModel;
    use app\member\model\PaymentConfModel;
    use app\payment\model\PaymentInfoModel;
    use app\payment\model\WalletModel;
    use think\Db;

    class Index extends Admin
    {

        protected $members = [];

        /**
         * @return mixed
         * @throws \think\Exception
         * @throws \think\exception\DbException
         */
        public function index()
        {

            // 查询
            $map = $this->getMap();

            // 排序
            $order = $this->getOrder('m.id asc');
            // 数据列表
            $data_list  = WalletProductModel::getObjectData()->where($map)->order($order)->paginate();
            $data_count = WalletProductModel::data_count($map);
            //            payment_conf

            //顶部按钮
            $TopButtons = [
                'member_num'    => [
                    'class' => 'btn btn-primary',
                    'title' => '用 户 数：' . MemberModel::where($map)->count(),
                ],
                'member_money'  => [
                    'class' => 'btn btn-danger',
                    'title' => '钱 包:' . $data_count['money'],
                    //                    'href'  => url('/index/index'),
                ],
                'member_point'  => [
                    'class' => 'btn btn-warning',
                    'title' => '积 分：' . $data_count['point'] / 100,
                    //                    'href'  => url('/index/index'),
                ],
                'member_pt_num' => [
                    'class' => 'btn btn-info',
                    'title' => '山桐子：' . $data_count['num'],
                    //                    'href'  => url('/index/index'),
                ],
                'member_lock'   => [
                    'class' => 'btn btn-success',
                    'title' => '锁 仓：' . $data_count['lock_num'],
                    //                    'href'  => url('/index/index'),
                ],
                'member_reward' => [
                    'class' => 'btn btn-primary',
                    'title' => '奖 励：' . $data_count['reward_num'] / 100,
                    //                    'href'  => url('/index/index'),
                ],
                'Excel'         => [
                    'title' => '导出Excel',
                    'href'  => url('excel')
                ],
            ];

            // 使用ZBuilder快速创建数据表格
            return ZBuilder::make('table')->setSearchArea([
                ['text','id','用户ID'],
                ['text','phone','用户手机号'],
                //                ['daterange','create_time','注册时间','','',['min-date' => '2018-10-10']]
            ])// 设置搜索框
            ->addTopButtons($TopButtons)->addColumns([ // 批量添加数据列
                                                       ['id','ID'],
                                                       ['aliplay_name','姓名'],
                                                       ['phone','手机号码','text','href' => url('/index/index')],
                                                       ['money','钱包','text'],
                                                       ['point','积分','text'],
                                                       ['num','数量','text'],
                                                       ['lock_num','锁仓','text'],
                                                       ['reward_num','奖励','callback','view_money'],
                                                       ['status','状态','status','',['冻结','启动']],
                                                       ['create_time','注册时间','datetime','','/d H:i:s'],
                                                       ['right_button','操作','btn']
            ])//
            ->addRightButtons([
                'view' => [
                    'title' => '查看详情',
                    'href'  => url('view',['id' => '__id__'])
                ]
            ])// 批量添加右侧按钮
            ->addOrder('phone,money,point,lock_num,reward_num,num')->setRowList($data_list)// 设置表格数据
            ->fetch(); // 渲染模板
        }

        public function excel()
        {


            // 数据列表
            $list = WalletProductModel::getObjectData()->select();

            $data = [];
            foreach ($list as $key => $iem)
            {


                //审核状态0审核中1审核失败2审通过3撤单
                $data[$key]['phone']      = $iem['phone'];
                $data[$key]['money']      = round($iem['money'] / 100,2);
                $data[$key]['point']      = round($iem['point'] / 100,2);
                $data[$key]['lock_num']   = $iem['lock_num'];
                $data[$key]['num']        = $iem['num'];
                $data[$key]['reward_num'] = round($iem['reward_num'] / 100,2);

                $data[$key]['member_id']    = $iem['member_id'];
                $data[$key]['bank_name']    = $iem['bank_ture_name'] . '-' . $iem['bank_name'] . '-' . $iem['bank_card_number'];
                $data[$key]['aliplay_name'] = $iem['aliplay_name'] . '-' . $iem['aliplay_account'];
                $data[$key]['update_time']  = date("Y-m-d H:i:s",$iem['update_time']);
                $data[$key]['create_time']  = date("Y-m-d H:i:s",$iem['create_time']);

            }

            //                        echo json_encode($data);
            //                        exit;
            // 查询数据

            // 设置表头信息（对应字段名,宽度，显示表头名称）
            $cellName = [
                ['member_id','auto','用户ID'],
                ['phone','auto','手机号码'],
                ['money','auto','余额'],
                ['point','auto','积分'],
                ['num','auto','山桐子'],
                ['lock_num','auto','锁仓'],
                ['reward_num','auto','奖励'],
                ['bank_name','auto','银行'],
                ['aliplay_name','auto','支付宝'],
                ['create_time','auto','注册时间 '],
            ];
            $time     = date("Y-m-d H:i:s",time());
            // 调用插件（传入插件名，[导出文件名、表头信息、具体数据]）
            plugin_action('Excel/Excel/export',[$time . '用户',$cellName,$data]);

        }

        /**
         * 详情
         *
         * @param null $id
         *
         * @return mixed
         */
        public function view($id = null)
        {

            //            $this->check_data($id);//验证数据

            if ($id === null)
                $this->error('缺少参数');
            $member                   = CheckDataModel::member($id);
            $memberlevel              = CheckDataModel::memberlevel($id);
            $member_info              = CheckDataModel::member_info($id);
            $payment_wallet           = CheckDataModel::payment_wallet($id);
            $base_wallet_product      = CheckDataModel::base_wallet_product($id);
            $base_wallet_product_lock = CheckDataModel::base_wallet_product_lock($id);

            $payment_conf = CheckDataModel::order($id);
            $order        = CheckDataModel::order($id);
            $order_limit  = CheckDataModel::order_limit($id);
            $topup        = CheckDataModel::topup($id);
            $withdraw     = CheckDataModel::withdraw($id);
            $shareReward  = CheckDataModel::shareReward($id);
            $paymentConf  = PaymentConfModel::where(['member_id' => $id])->find();


            $group = MemberModel::getMemberGroup($id);
            $this->assign('member',$member);
            $this->assign('memberlevel',$memberlevel);
            $this->assign('member_info',$member_info);
            $this->assign('payment_wallet',$payment_wallet);
            $this->assign('base_wallet_product',$base_wallet_product);
            $this->assign('payment_conf',$payment_conf);
            $this->assign('paymentConf',$paymentConf);
            $this->assign('base_wallet_product_lock',$base_wallet_product_lock);

            $this->assign('order',$order);
            $this->assign('order_limit',$order_limit);
            $this->assign('topup',$topup);
            $this->assign('withdraw',$withdraw);
            $this->assign('shareReward',$shareReward);

            $difference = (($topup['statistics']['amount'] - $order['statistics']['buy_money'] + $order['statistics']['seller_money'] - $withdraw['statistics']['amount'] - $payment_wallet['money'] - $order_limit['statistics']['buy_money']) / 100);

            $this->assign('group',$group);
            $this->assign('difference',$difference);
            //                         $this->save_data();
            return $this->fetch();

        }

        public function details($id = null)
        {


            if ($id === null)
                $this->error('缺少参数');
            $member              = CheckDataModel::member($id);
            $member_info         = CheckDataModel::member_info($id);
            $payment_wallet      = CheckDataModel::payment_wallet($id);
            $base_wallet_product = CheckDataModel::base_wallet_product($id);
            $payment_conf        = CheckDataModel::order($id);
            $order               = CheckDataModel::order($id);
            $order_limit         = CheckDataModel::order_limit($id);
            $topup               = CheckDataModel::topup($id);
            $withdraw            = CheckDataModel::withdraw($id);
            $shareReward         = CheckDataModel::shareReward($id);
            $paymentConf         = PaymentConfModel::where(['member_id' => $id])->find();


            $this->members = MemberModel::where('')->select();

            $this->assign('member',$member);
            $this->assign('member_info',$member_info);
            $this->assign('payment_wallet',$payment_wallet);
            $this->assign('base_wallet_product',$base_wallet_product);
            $this->assign('payment_conf',$payment_conf);
            $this->assign('paymentConf',$paymentConf);

            $this->assign('order',$order);
            $this->assign('order_limit',$order_limit);
            $this->assign('topup',$topup);
            $this->assign('withdraw',$withdraw);
            $this->assign('shareReward',$shareReward);

            $difference = (($topup['statistics']['amount'] - $order['statistics']['buy_money'] + $order['statistics']['seller_money'] - $withdraw['statistics']['amount'] - $payment_wallet['money'] - $order_limit['statistics']['buy_money']) / 100);
            $group      = UtilTree::toLayer($this->members,$id);
            $group      = empty($group) ? false : $group[0];
            $this->assign('group',$group);
            $this->assign('difference',$difference);
            //                         $this->save_data();
            return $this->fetch('details');

        }

        /**
         * 用户资产是否正常
         */
        public function save_data()
        {

            $MemberModel = MemberModel::where([])->select();

            foreach ($MemberModel as $item)
            {
                $this->member_info($item->id);
                $payment_wallet = $this->payment_wallet($item->id);
                $this->base_wallet_product($item->id);
                $this->order($item->id);

                $order       = $this->order($item->id);
                $order_limit = $this->order_limit($item->id);
                $topup       = $this->topup($item->id);
                $withdraw    = $this->withdraw($item->id);

                $difference = (($topup['statistics']['amount'] - $order['statistics']['buy_money'] + $order['statistics']['seller_money'] - $withdraw['statistics']['amount'] - $payment_wallet['money'] - $order_limit['statistics']['buy_money']) / 100);
                if (Db::name('face2market_member_diffe')->where(['member_id' => $item->id])->find())
                {
                    Db::name('face2market_member_diffe')->where(['member_id' => $item->id])->update([
                        'member_id' => $item->id,
                        'data'      => json_encode([
                            $topup['statistics']['amount'],
                            $order['statistics']['buy_money'],
                            $order['statistics']['seller_money'],
                            $withdraw['statistics']['amount'],
                            $payment_wallet['money'],
                            $order_limit['statistics']['buy_money']
                        ]),
                        'diffe'     => $difference
                    ]);
                }
                else
                {
                    Db::name('face2market_member_diffe')->insert([
                        'member_id' => $item->id,
                        'data'      => json_encode([
                            $topup['statistics']['amount'],
                            $order['statistics']['buy_money'],
                            $order['statistics']['seller_money'],
                            $withdraw['statistics']['amount'],
                            $payment_wallet['money'],
                            $order_limit['statistics']['buy_money']
                        ]),
                        'diffe'     => $difference
                    ]);
                }

            }
        }

        /**
         * 用户表
         *
         * @param $id
         *
         * @return array|false|\PDOStatement|string|\think\Model
         */
        protected function member($id)
        {

            $MemberModel = MemberModel::where(['id' => $id])->find();
            UtilTree::config([
                'title' => 'phone',
                'pid'   => 'phone_puid'
            ]);
            $group = UtilTree::toLayer($this->members,$id);
            $group = empty($group) ? false : $group[0];
            $this->assign('group',$group);

            return $MemberModel;
        }

        /**
         * 用户信息
         *
         * @param $id
         *
         * @return array|false|\PDOStatement|string|\think\Model
         */
        protected function member_info($id)
        {

            return MemberInfoModel::where(['member_id' => $id])->find();
        }

        protected function payment_conf($id)
        {

            return PaymentInfoModel::where(['member_id' => $id])->find();
        }

        protected function payment_wallet($id)
        {

            return WalletModel::where(['member_id' => $id])->find();
        }

        protected function base_wallet_product($id)
        {

            return WalletProductModel::where(['member_id' => $id])->column('product_id as id,product_num');
        }

        /**
         * 用户挂单
         *
         * @param $id
         *
         * @return mixed
         */
        protected function order_limit($id)
        {

            $face2market_order_limit = Db::view('face2market_order_limit',true)//字段
            ->view('member','phone','member.id = face2market_order_limit.member_id','left')//
            ->where(['face2market_order_limit.member_id' => $id])->order('face2market_order_limit.create_time','desc')->paginate(5);
            $data['data']            = $face2market_order_limit;
            $data['page']            = $face2market_order_limit->render();
            $data['statistics']      = [
                'buy_money' => Db::name('face2market_order_limit')->field('(residue_number * price) as buy_money')->where([
                    'member_id' => $id,
                    'status'    => 0
                ])->find()['buy_money'],
                'buy_pro'   => Db::name('face2market_order_limit')->where([
                    'member_id' => $id,
                    'status'    => 1
                ])->sum('residue_number'),
            ];

            return $data;
        }

        /**
         * 用户交易记录
         *
         * @param $id
         *
         * @return mixed
         */
        protected function order($id)
        {

            $face2market_order = Db::view('face2market_order',true)//字段
            ->view('member m1','phone as buyer','m1.id = face2market_order.buyer_id','LEFT')//
            ->view('member m2','phone as seller','m2.id = face2market_order.seller_id','LEFT')//
            ->where(['m2.id' => $id,'del' => 0])->whereOr(['m1.id' => $id])->where(['face2market_order.del' => 0,])//
            ->order('face2market_order.create_time','desc')->paginate(5);

            $data['data']       = $face2market_order;
            $data['page']       = $face2market_order->render();
            $data['statistics'] = [
                'buy_pro'      => Db::name('face2market_order')->where([
                    'buyer_id' => $id,
                    'status'   => 1,
                    'del'      => 0
                ])->sum('number'),
                'buy_money'    => Db::name('face2market_order')->where([
                    'buyer_id' => $id,
                    'status'   => 1,
                    'del'      => 0
                ])->sum('amount'),
                'seller_pro'   => Db::name('face2market_order')->where([
                    'seller_id' => $id,
                    'status'    => 1,
                    'del'       => 0
                ])->sum('number'),
                'seller_money' => Db::name('face2market_order')->where([
                    'seller_id' => $id,
                    'status'    => 1,
                    'del'       => 0
                ])->sum('amount'),
            ];

            return $data;
        }

        /**
         * 充值
         *
         * @param $id
         *
         * @return mixed
         */
        protected function topup($id)
        {

            $payment_pay        = Db::view('payment_pay',true)//字段
            ->view('member','phone','member.id = payment_pay.member_id','left')//
            ->where([
                'payment_pay.member_id' => $id,
                'payment_pay.status'    => 1
            ])->order('payment_pay.create_time','desc')->paginate();
            $data['data']       = $payment_pay;
            $data['page']       = $payment_pay->render();
            $data['statistics'] = [
                'amount' => Db::name('payment_pay')->where(['member_id' => $id,'status' => 1])->sum('money'),
            ];
            return $data;
        }

        /**
         * 用户提现
         *
         * @param $id
         *
         * @return mixed
         */
        protected function withdraw($id)
        {

            $payment_withdraw = Db::view('payment_withdraw',true)//字段
            ->view('member','phone','member.id = payment_withdraw.member_id','left')//
            ->where([
                'payment_withdraw.member_id' => $id
            ])->whereIn('payment_withdraw.status',[0,2,4])->order('payment_withdraw.create_time','desc')->paginate();

            $data['data']       = $payment_withdraw;
            $data['page']       = $payment_withdraw->render();
            $data['statistics'] = [
                'amount' => Db::name('payment_withdraw')->where(['member_id' => $id])->whereIn('status',[
                    0,
                    2,
                    4
                ])->sum('amount_money'),
            ];
            return $data;
        }

        /**
         * 验证用户资产
         *
         * @param $id
         */
        public function check_data($id)
        {


            $time = date('Y-m-d',time());
            $str  = strtotime(date('Y-m-d' . '00:00:00',strtotime($time)));
            $end  = strtotime(date('Y-m-d' . '23:59:00',strtotime($time)));
            //获取数据
            $query_data = CheckPresentDataModel::query_data($id,$str,$end);

            $CheckPresentDataModel = CheckPresentDataModel::where(['member_id' => $id])->find();
            if ($CheckPresentDataModel)
            {
                $json_decode = json_decode($CheckPresentDataModel['data'],true);


                $query_data['get_member_topup'] = $query_data['get_member_topup'] + $json_decode['get_member_topup'];

                $query_data['get_order_limit']['buy_money']          = $query_data['get_order_limit']['buy_money'] + $json_decode['get_order_limit']['buy_money'];
                $query_data['get_face2market_order']['seller_money'] = $query_data['get_face2market_order']['seller_money'] + $json_decode['get_face2market_order']['seller_money'];
                $query_data['get_face2market_order']['buy_money']    = $query_data['get_face2market_order']['buy_money'] + $json_decode['get_face2market_order']['buy_money'];
                $query_data['get_withdraw']                          = $query_data['get_withdraw'] + $json_decode['get_withdraw'];
                $query_data['get_payment_wallet']['money']           = $query_data['get_payment_wallet']['money'] + $json_decode['get_payment_wallet']['money'];
                $query_data['tady_money']                            = $json_decode['get_payment_wallet']['money'];
                $query_data['assets_check']                          = $query_data['get_member_topup']//
                    + $query_data['get_face2market_order']['seller_money']//
                    - $query_data['get_face2market_order']['buy_money']//
                    - $query_data['get_order_limit']['buy_money']//
                    - $query_data['get_withdraw'] //
                    - $query_data['get_payment_wallet']['money'] //
                    + $query_data['tady_money'];
            }

            $this->assign('query_data',$query_data);
        }
    }